# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[ -n "${gbmc_ncsi_br_pub_addr_lib-}" ] && return

[ ! -e /usr/share/gbmc-br-lib.sh ] && return

source /usr/share/network/lib.sh || exit
source /usr/share/gbmc-br-lib.sh || exit

gbmc_ncsi_br_pub_addr_init=
gbmc_ncsi_br_pub_addr_lastip=
gbmc_ncsi_br_pub_addr_confip=

gbmc_ncsi_br_pub_addr_update() {
  [ -n "$gbmc_ncsi_br_pub_addr_init" ] || return
  [ "$gbmc_ncsi_br_pub_addr_confip" != "$gbmc_ncsi_br_pub_addr_lastip" ] || return
  gbmc_ncsi_br_pub_addr_confip="$gbmc_ncsi_br_pub_addr_lastip"

  printf 'gBMC Bridge Pub Addr from NCSI: %s\n' \
    "${gbmc_ncsi_br_pub_addr_lastip:-(deleted)}" >&2

  local pfx_bytes=()
  if [ -n "$gbmc_ncsi_br_pub_addr_lastip" ]; then
    ip_to_bytes pfx_bytes "$gbmc_ncsi_br_pub_addr_lastip"
    # Ensure we have a /64 or an fdxx address
    if (( pfx_bytes[8] != 0xfd || pfx_bytes[9] == 0 )); then
      local i
      for (( i = 8; i < 16; ++i )); do
        if (( pfx_bytes[$i] != 0 )); then
          pfx_bytes=()
          break
        fi
      done
    fi
  fi

  local contents=
  if (( ${#pfx_bytes[@]} != 0 )); then
    pfx_bytes[8]=0xfd
    # We never want to use the stateless pfx
    if (( pfx_bytes[9] == 0 )); then
      pfx_bytes[9]=0x01
    fi
    # Remove any existing persisted IP
    gbmc_br_set_ip
    # Load the IP to the bridge non-persistently
    gbmc_br_reload_ip "$(ip_bytes_to_str pfx_bytes)"
  else
    gbmc_br_reload_ip
  fi
}

gbmc_ncsi_br_pub_addr_hook() {
  if [ "$change" = 'init' ]; then
    gbmc_ncsi_br_pub_addr_init=1
    gbmc_ip_monitor_defer
  elif [ "$change" = 'defer' ]; then
    gbmc_ncsi_br_pub_addr_update
  elif [ "$change" = 'addr' -a "$intf" = '@NCSI_IF@' ] &&
     [ "$scope" = 'global' -a "$fam" = 'inet6' ] &&
     [[ "$flags" != *deprecated* ]]; then
    if [ "$action" = 'add' -a "$ip" != "$gbmc_ncsi_br_pub_addr_lastip" ]; then
      gbmc_ncsi_br_pub_addr_lastip="$ip"
      gbmc_ip_monitor_defer
    fi
    if [ "$action" = 'del' -a "$ip" = "$gbmc_ncsi_br_pub_addr_lastip" ]; then
      gbmc_ncsi_br_pub_addr_lastip=
      gbmc_ip_monitor_defer
    fi
  fi
}

GBMC_IP_MONITOR_HOOKS+=(gbmc_ncsi_br_pub_addr_hook)

gbmc_ncsi_br_pub_addr_lib=1
